﻿using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media;
using StringReader = System.IO.StringReader;

namespace FAQ_UI
{
	public abstract class ViewHolder : INotifyPropertyChanged
	{
		public static DependencyProperty k = DependencyProperty.Register("ViewHolder", typeof(ViewHolder), typeof(UIElement));
		private UIElement view;

		public event PropertyChangedEventHandler PropertyChanged;

		public static UIElement parse(string path)
		{
			Uri uri = new Uri(path, System.UriKind.RelativeOrAbsolute);
			using (Stream stream = App.GetResourceStream(uri).Stream)
			{
				return (UIElement)XamlReader.Load(stream);
			}
			/*byte[] buf = new byte[1024];
             ByteArrayOutputStream baos=new ByteArrayOutputStream();
             int i = 0;
             while ((i = stream.Read(buf,0,buf.Length)) != 0)
             {
                 baos.write(buf, 0, i);
             }
             System.Console.WriteLine(baos.ToString());*/
		}

		public void setView(UIElement e)
		{
			this.view = e;
			view.SetValue(k, this);
			view.SetValue(FrameworkElement.DataContextProperty, this);
		}

		public static string save(UIElement element)
		{
			return System.Windows.Markup.XamlWriter.Save(element);
		}

		public static UIElement Clone(string savedObject)
		{
			System.IO.StringReader stringReader = new StringReader(savedObject);
			System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(stringReader);
			UIElement target = (UIElement)System.Windows.Markup.XamlReader.Load(xmlReader);
			return target;
		}

		public void OnPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
		}

		public static T FindChild<T>(DependencyObject obj, string name) where T : FrameworkElement
		{
			for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
			{
				DependencyObject child = VisualTreeHelper.GetChild(obj, i);
				if (child != null && child is T && (child as T).Name.Equals(name))
					return (T)child;
				else
				{
					T childOfChild = FindChild<T>(child, name);
					if (childOfChild != null)
						return childOfChild;
				}
			}
			return null;
		}

		public UIElement get()
		{
			return view;
		}

		public T get<T>(string namw) where T : FrameworkElement
		{
			return FindChild<T>(get(), namw);
		}

		public abstract ViewHolder newInstance();

		public abstract void set(int i, object data, IList datalist);

		public void AddChild(object value)
		{
			throw new NotImplementedException();
		}

		public void AddText(string text)
		{
			throw new NotImplementedException();
		}
	}
}